package net.dgg.zz.credential.generalCredential.controller;

import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.service.OrfApiService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.datatable.DataTableUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.tmd.foundation.platform.annotation.AuthOpt;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.dao.ProductDao;
import net.dgg.zz.common.entity.OrderProductVo;
import net.dgg.zz.common.entity.Product;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.service.ProductService;
import net.dgg.zz.common.utils.*;
import net.dgg.zz.common.utils.excel.ExcelUtils;
import net.dgg.zz.credential.baseCredential.entity.BaseCredential;
import net.dgg.zz.credential.baseCredential.service.BaseCredentialService;
import net.dgg.zz.credential.certificateProduct.service.CertificateProductService;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.generalCredential.entity.*;
import net.dgg.zz.credential.generalCredential.service.GeneralCredentialService;
import net.dgg.zz.credential.guidePriceConfigure.service.GuidePriceConfigService;
import net.dgg.zz.credential.storageCapacity.entity.StorageCapacity;
import net.dgg.zz.credential.storageCapacity.service.StorageCapacityService;
import net.dgg.zz.credential.warningConfigure.service.SystemConfigureService;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.fblock.log.NLog;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

/**
 * 证书管理
 *
 * @author wmj
 * @date 2018/8/13 10:54
 */
@Controller
@RequestMapping("/zs/general_credential")
public class GeneralCredentialController extends DggBaseController {

    @Resource
    private ProductService productService;

    @Resource
    private CommonService commonService;

    @Resource
    private GeneralCredentialService generalCredentialService;

    @Resource
    private BaseCredentialService baseCredentialService;

    @Resource
    private OrfApiService orfApiService;

    @Resource
    private CertificateProductService certificateProductService;

    @Resource
    private StorageCapacityService storageCapacityService;

    @Resource
    private SystemConfigureService systemConfigureService;

    @Resource
    private GuidePriceConfigService guidePriceConfigService;
    @Resource
    private SessionManager sessionManager;
    @Resource
    private DesUtil desUtil;
    @Resource
    private ProductDao productDao;
    /**
     * 证书待新增列表
     */
    @NLog()
    @RequestMapping("/wait_add_page")
    public String waitAddPage(Model model) {
        // 付款类型
        List<Map> payMethods = commonService.queryTreeBook(ScProductConstant.ORF_FKFS, 1, 2, null);
        model.addAttribute("payMethods", payMethods);
        // 付款状态
        List<Map> costStates = commonService.queryTreeBook(ScProductConstant.PRODUCT_CHARGE_STATE, 1, 2, null);
        model.addAttribute("costStates", costStates);

        return "/zzsc/credential/generalCredential/wait_add_page";
    }

    /**
     * 证书待新增列表数据
     *
     * @return
     * @Param
     */
    @NLog()
    @RequestMapping(value = "/wait_add_data", method = RequestMethod.POST)
    @ResponseBody
    public DataTableResponse queryWaitAddCredential(@RequestParam Map params, HttpServletRequest request) {
        try {
            DataTableRequest r = DataTableUtils.getParam(request);
            params.put("relevanceCredential", "0");
            params.put("businessProductCode", ScProductConstant.CHARGE_CARD);
            params.put("page", r.getPage());//获取当前页
            params.put("limit", r.getLength());//获取每页条数

            Map fileMap = new HashMap();
            fileMap.put("orderTime", "p.order_time");
            OrderHandleUtils.getOrderCol(r, params, fileMap);

            List<OrderProductVo> products = productService.findWaitAddCredentailProductWithPage(params);
            Integer count = Integer.parseInt(params.get("count").toString());
            return new DataTableResponse().data(params, products);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new DataTableResponse().data(params, null);
        }

    }

    /**
     * 证书新增页面
     */
    @NLog()
    @RequestMapping("/add_credential_page")
    public String addCredentialPage(@RequestParam Map params, Model model) {
        // 查询需要新增证书关联的订单详情
        List<OrderProductVo> products = productService.findWaitAddCredentailProduct(params);
        model.addAttribute("products", products.get(0));
        // 获取当前日期
        model.addAttribute("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));

        // 适用范围
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        // 证书类别
        List<Map> certificateCategorys = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_CATEGORY, 1, 2, null);
        model.addAttribute("certificateCategorys", certificateCategorys);
        // 三类证书
        List<Map> certificateToThrees = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_TO_THREE, 1, 2, null);
        model.addAttribute("certificateToThrees", certificateToThrees);
        // 是否购买社保
        List<CommonVo> socialSecurity = new ArrayList<>(2);
        CommonVo commonVo1 = new CommonVo("0","是");
        CommonVo commonVo2 = new CommonVo("1","否");
        socialSecurity.add(commonVo1);
        socialSecurity.add(commonVo2);
        model.addAttribute("socialSecurity", socialSecurity);
        model.addAttribute("ceretificateId", DggKeyWorker.nextId());
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        return "/zzsc/credential/generalCredential/add_credential";
    }

    /**
     * 证书新增验证
     *
     * @param params
     * @return
     */
    @NLog()
    @RequestMapping(value = "/add_certificate_check", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse addCertificateCheck(@RequestParam Map params) {
        try {
            // 验证订单状态
            OrderProductVo orderProductVo = productService.checkProduct(params);
            // 验证资金池
//            Boolean result = systemConfigureService.checkCaptialPool(orderProductVo.getProductOrgId());
//            if (result) {
//                return this.getSuccessResponse("通过");
//            } else {
//                return this.getFailResponse("事业部现有资金池额度小于0，不能新增证书！");
//            }
            return this.getSuccessResponse("通过");
        } catch (CertificateExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * 状态栏新增入库
     *
     * @param params
     * @return
     */
    @NLog()
    @RequestMapping(value = "/add_certificate_check1", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse addCertificateCheck1(@RequestParam Map params) {
        try {
            // 验证订单状态
            OrderProductVo orderProductVo = productService.checkProduct(params);
            return this.getSuccessResponse("通过");
        } catch (CertificateExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * 新增证书
     *
     * @param generalCertificate
     * @param params
     * @return
     */
    @NLog()
    @RequestMapping(value = "/add_certificate", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse addCertificate(GeneralCertificate generalCertificate, @RequestParam Map params) throws ParseException, IllegalAccessException, InvocationTargetException {
        generalCertificate.setGeneralType(CredentialConstant.GENERAL_CREDENTIAL);
        params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        List<StorageCapacity> storageCapacities = generalCredentialService.saveOrUpdateCertificate(generalCertificate, params);
        params.put("msg", "证书新增成功,点击确认跳转至证书信息列表！");
        try {
            BaseCredential baseCredential = generalCredentialService.boundProductReservation(generalCertificate.getId(), storageCapacities, false);
            if (StringUtils.isNotEmpty(baseCredential)) {
                params.put("msg", "证书新增成功并已绑定生产订单[" + baseCredential.getScOrderNo() + "],点击确认跳转至证书信息列表！");
            }
        } catch (CertificateExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("证书新增成功，证书自动绑定预订生产订单失败！");
        }
        return this.getSuccessResponse(params);
    }

    /**
     * 证书信息列表
     */
    @NLog()
    @RequestMapping("/general_certificate_info")
    public String generalCertificateInPage(@RequestParam Map params, Model model) {
        // 适用范围
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        // 证书类别
        List<Map> certificateCategorys = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_CATEGORY, 1, 2, null);
        model.addAttribute("certificateCategorys", certificateCategorys);
        // 证书状态
        List<Map> generalCredentialStatus = commonService.queryTreeBook(CredentialConstant.GENERAL_CREDENTIAL_STATUS, 1, 2, null);
        model.addAttribute("generalCredentialStatus", generalCredentialStatus);
        List<Map> libraryStatus = commonService.queryTreeBook(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS, 1, 2, null);
        model.addAttribute("libraryStatus", libraryStatus);
        // 超期类型
        List<Map> overDueType = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE, 1, 2, null);
        model.addAttribute("overDueType", overDueType);
        // 收证类型
        model.addAttribute("receiptType", applicationScopes);
        // 是否购买社保
        List<CommonVo> socialSecurity = new ArrayList<>(2);
        CommonVo commonVo1 = new CommonVo("0","是");
        CommonVo commonVo2 = new CommonVo("1","否");
        socialSecurity.add(commonVo1);
        socialSecurity.add(commonVo2);
        model.addAttribute("socialSecurity", socialSecurity);
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        model.addAttribute("createTime", params.containsKey("createTime") && StringUtils.isNotEmpty(params.get("createTime")) ? params.get("createTime") : null);
        model.addAttribute("generalCredentialStatu", params.containsKey("generalCredentialStatus") && StringUtils.isNotEmpty(params.get("generalCredentialStatus")) ? params.get("generalCredentialStatus") : null);
        model.addAttribute("libraryStatu", params.containsKey("libraryStatus") && StringUtils.isNotEmpty(params.get("libraryStatus")) ? params.get("libraryStatus") : null);
        model.addAttribute("scope", params.containsKey("applicationScopes") && StringUtils.isNotEmpty(params.get("applicationScopes")) ? params.get("applicationScopes") : null);
        model.addAttribute("keywords", params.containsKey("keywords") && StringUtils.isNotEmpty(params.get("keywords")) ? params.get("keywords") : null);
        model.addAttribute("overdueStatu", params.containsKey("overdueStatus") && StringUtils.isNotEmpty(params.get("overdueStatus")) ? params.get("overdueStatus") : null);
        model.addAttribute("overdueTypes", params.containsKey("overdueType") && StringUtils.isNotEmpty(params.get("overdueType")) ? params.get("overdueType") : null);
        return "/zzsc/credential/generalCredential/general_certificate_info";
    }

    /**
     * 证书信息列表数据
     *
     * @param params
     * @param request
     * @return
     */
    @NLog()
    @RequestMapping("/general_certificate_info_data")
    @ResponseBody
    public DataTableResponse generalCertificateInfo(@RequestParam Map params, HttpServletRequest request) {
        try {
            DataTableRequest r = DataTableUtils.getParam(request);
            r.getOrder();
            params.put("page", r.getPage());//获取当前页
            params.put("limit", r.getLength());//获取每页条数
            List<GeneralCertificate> generalCertificates;
            String matchFlag = "";
            if (StringUtils.isNotEmpty(params.get("matchFlag"))) {//这里表示证书匹配的搜索传了条件进来
                matchFlag = params.get("matchFlag").toString();
            }
            if ("0".equals(matchFlag)) {//表示初始化进来
                generalCertificates = new ArrayList<>();
                params.put("count", 0);
                return new DataTableResponse().data(params, generalCertificates);
            } else {//其他情况如:证书信息列表或者点了搜索后的匹配页面进入
                params.put("createTime", params.containsKey("createTime") && StringUtils.isNotEmpty(params.get("createTime")) ? new Date() : null);
                // 反序列化 专业多选
                if(params.get("certificateSpecialtysArray") != null){
                    if(params.get("certificateSpecialtysArray").toString().contains("[")){
                        params.put("certificateSpecialtysArray", Arrays.asList(params.get("certificateSpecialtysArray").toString().substring(2, params.get("certificateSpecialtysArray").toString().length() -2).split("\",\"")));
                    } else {
                        params.put("certificateSpecialtysArray", Arrays.asList(params.get("certificateSpecialtysArray").toString().substring(1, params.get("certificateSpecialtysArray").toString().length() - 1)));
                    }
                }
                // 去除空值
                Iterator iterator = params.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    if(StringUtils.isEmpty(entry.getValue())){
                        iterator.remove();
                    }
                }
                generalCertificates = generalCredentialService.queryGertificateInfo(params);
                return new DataTableResponse().data(params, generalCertificates);
            }
        } catch (CommonExcption e) {
            e.printStackTrace();
            params.put("count", 0);
            return new DataTableResponse().data(params, new ArrayList<GeneralCertificate>());
        }catch (Exception e) {
            e.printStackTrace();
            params.put("count", 0);
            return new DataTableResponse().data(params, new ArrayList<GeneralCertificate>());
        }
    }




    /**
     * 证书导出
     * @param params
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export_credential")
    @ResponseBody
    @NLog()
    public void exportCredential(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<GeneralCredentialVo> list = generalCredentialService.queryExportCredential(params);
            String fileName = "证书信息列表数据_" + DateUtils.dateString(new Date(), "yyyyMMddHHmm") + ".xlsx";
            ExcelUtils.writeToFile(list, null, fileName, response, GeneralCredentialVo.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    /*
     * @Author zsx
     * @Date 2018-08-27 06:08:25
     * @Description 退回证书列表初始化
     * @return String
     */
    @RequestMapping("/return_certificate_list")
    @AuthOpt(code = "RETURN_CERTIFICATE_LIST")
    @NLog
    public String returnCertificateList(Model model) {
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        return "/zzsc/credential/returnCertificate/return_certificate_list";
    }

    /*
     * @Author zsx
     * @Date 2018-08-27 06:08:51
     * @Description 分页查询证书退回列表数据
     * @param params
     * @return DataTableResponse
     */
    @RequestMapping("/get_return_certificate")
    @ResponseBody
    @NLog
    public DataTableResponse getReturnCertificate(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        try {
            DataTableRequest r = DataTableUtils.getParam(request);
            params.put("page", r.getPage());
            params.put("limit", r.getLength());
            if(params.containsKey("personalPhone") && !StringUtils.isEmpty(params.get("personalPhone"))) {
                params.put("personalPhone", desUtil.encrypt(params.get("personalPhone").toString()));
            }
            List<GeneralCertificate> certificates = generalCredentialService.selectReturnCertificateByWithPage(params);
            return new DataTableResponse().data(params, certificates);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new DataTableResponse().data(params, null);
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-28 10:08:42
     * @Description 导出退回证书
     */
    @RequestMapping("/export_return_credential")
    @ResponseBody
    @NLog
    public void exportReturnCredential(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        try {
            if(params.containsKey("personalPhone") && !StringUtils.isEmpty(params.get("personalPhone"))) {
                params.put("personalPhone", desUtil.encrypt(params.get("personalPhone").toString()));
            }
            List<ReturnCertificateVo> returnCertificateVos = generalCredentialService.selectExportRetenCredential(params);
            for (ReturnCertificateVo dto : returnCertificateVos) {
                dto.setCertificateArea((dto.getAreaProvince() == null ? "" : dto.getAreaProvince()) + "/" + (dto.getCertificateArea() == null ? "" : dto.getCertificateArea()));
                dto.setRetenTime(DateUtils.dateString(dto.getLastOutgoingTime(), DateUtils.yyyy_MM_dd));
            }
            String fileName = "退回证书信息列表" + DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss) + ".xlsx";
            ExcelUtils.writeToFile(returnCertificateVos, null, fileName, response, ReturnCertificateVo.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 验证证书出入库状态
     *
     * @return
     */
    @NLog()
    @RequestMapping("/check_library_status")
    @ResponseBody
    public DggRestResponse checkLibraryStatus(@RequestParam Long id, @RequestParam String libraryStatus) {
        try {
            ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "证书id不能为空");
            generalCredentialService.checkCredentialStatus(id, libraryStatus);
            return this.getSuccessResponse("可进行出入库操作");
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return this.getFailResponse(c.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员！");

        }
    }

    /**
     * 出库页面
     *
     * @param id
     * @return
     */
    @NLog()
    @RequestMapping("/get_out_page")
    public String getOutPage(@RequestParam Long id, Model model) {
        try {
            ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "证书id不能为空");
            GeneralCertificate credential = generalCredentialService.findCredentialById(id);
            // 证书类别
            List<Map> outGoingReason = commonService.queryTreeBook(CredentialConstant.OUT_GOING_REASON, 1, 2, null);
            // 如果证书状态不为未使用状态则将退回人才选项移除
            if (!credential.getCertificateStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE)) {
                Iterator<Map> it = outGoingReason.iterator();
                while (it.hasNext()) {
                    Map map = it.next();
                    if (CredentialConstant.OUT_GOING_REASON_TALENT_RETURN.equals(map.get("code"))) {
                        it.remove();
                    }
                }
            }
            model.addAttribute("outGoingReason", outGoingReason);

            // 证书出库
            List<Map> outboundDataType = commonService.queryTreeBook(CredentialConstant.OUTBOUND_DATA_TYPE, 1, 2, null);
            model.addAttribute("outboundDataType", outboundDataType);
            model.addAttribute("id", id);
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return "/error/500";
        } catch (Exception e) {
            e.printStackTrace();
            return "/error/500";
        }
        return "/zzsc/credential/generalCredential/get_out_page";
    }

    /**
     * 证书出库
     *
     * @param id
     * @param params
     * @return
     */
    @NLog
    @RequestMapping("/get_out")
    @ResponseBody
    public DggRestResponse getOut(@RequestParam Long id, @RequestParam Map params) {
        try {
            ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "证书id不能为空");
            GeneralCertificate generalCertificate = generalCredentialService.checkCredentialStatus(id, CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN);
            generalCredentialService.credentialGetOut(generalCertificate, params);
            return this.getSuccessResponse("出库成功！");
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return this.getFailResponse(c.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员！");
        }
    }


    /**
     * 入库页面
     *
     * @param id
     * @return
     */
    @NLog()
    @RequestMapping("/get_in_page")
    public String getInPage(@RequestParam Long id, Model model) {
        try {
            ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "证书id不能为空");
            // 证书类别
            List<Map> warehousingReason = commonService.queryTreeBook(CredentialConstant.WAREHOUSING_REASON, 1, 2, null);
            model.addAttribute("warehousingReason", warehousingReason);
            model.addAttribute("id", id);
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return "/error/401";
        } catch (Exception e) {
            e.printStackTrace();
            return "/error/401";
        }
        return "/zzsc/credential/generalCredential/get_in_page";
    }

    /**
     * 证书入库
     *
     * @param id
     * @param params
     * @return
     */
    @NLog
    @RequestMapping("/get_in")
    @ResponseBody
    public DggRestResponse getIn(@RequestParam Long id, @RequestParam Map params) {
        try {
            ValidateUtils.isTrue(StringUtils.isNotEmpty(id), CertificateExcption.class, "证书id不能为空");
            GeneralCertificate generalCertificate = generalCredentialService.checkCredentialStatus(id, CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_OUT);
            generalCredentialService.credentialGetIn(generalCertificate, params);
            return this.getSuccessResponse("出库成功！");
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return this.getFailResponse(c.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员！");
        }
    }


    /**
     * 编辑证书
     *
     * @param id
     * @return
     */
    @NLog()
    @RequestMapping("/edit_credential_page")
    public String editCredentialPage(@RequestParam Long id, Long productId,String talentRenewal, Model model) {
        try {
            GeneralCertificate credential = generalCredentialService.findCredentialById(id);
            model.addAttribute("credential", credential);
            if (StringUtils.isNotEmpty(talentRenewal)){
                // 人才续签

                // 查询需要新增证书关联的订单详情
                OrderProductVo product = productService.selectOrderProductVoByProductId(productId);
                if(product != null){
                    credential.setScOrderId(product.getScProductOrderId());
                    credential.setScOrderNo(product.getScProductOrderNo());
                    // 签单商务名称
                    model.addAttribute("signUserName",product.getSignUserName());
                    // 签单商务id
                    model.addAttribute("signUserId", product.getSignUserId());
                    // 合同编号
                    model.addAttribute("contractNo", product.getContractNo());
                } else {
                    // 签单商务名称
                    model.addAttribute("signUserName",credential.getCollectorName());
                    // 签单商务id
                    model.addAttribute("signUserId", credential.getCollectorId());
                    // 合同编号
                    model.addAttribute("contractNo", credential.getContractNo());
                }
            } else {
                // 编辑

                // 查询证书关联的订单
                OrderProductVo product = productService.selectOrderProductVoByProductId(credential.getScOrderId());
                if(product != null){
                    // 签单商务名称
                    model.addAttribute("signUserName",product.getSignUserName());
                    // 签单商务id
                    model.addAttribute("signUserId", product.getSignUserId());
                    // 合同编号
                    model.addAttribute("contractNo", product.getContractNo());
                } else {
                    // 签单商务名称
                    model.addAttribute("signUserName",credential.getCollectorName());
                    // 签单商务id
                    model.addAttribute("signUserId", credential.getCollectorId());
                    // 合同编号
                    model.addAttribute("contractNo", credential.getContractNo());
                }
            }
//            Product product = productService.findProductByOrderId(credential.getScOrderId(),1);
//            model.addAttribute("productId",product.getId());
            model.addAttribute("oldProductId",productId);
            // 人才续签标志
            model.addAttribute("talentRenewal", talentRenewal);
            // 获取当前日期
            model.addAttribute("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));

            // 适用范围
            List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
            model.addAttribute("applicationScopes", applicationScopes);
            // 证书类别
            List<Map> certificateCategorys = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_CATEGORY, 1, 2, null);
            model.addAttribute("certificateCategorys", certificateCategorys);
            // 三类证书
            List<Map> certificateToThrees = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_TO_THREE, 1, 2, null);
            model.addAttribute("certificateToThrees", certificateToThrees);
            // 是否购买社保
            List<CommonVo> socialSecurity = new ArrayList<>(2);
            CommonVo commonVo1 = new CommonVo("0","是");
            CommonVo commonVo2 = new CommonVo("1","否");
            socialSecurity.add(commonVo1);
            socialSecurity.add(commonVo2);
            model.addAttribute("socialSecurity", socialSecurity);

            model.addAttribute("credentialStatus", CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE);
            model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return "/error/401";
        } catch (Exception e) {
            e.printStackTrace();
            return "/error/401";
        }
        return "/zzsc/credential/generalCredential/edit_credential_page";
    }

    /**
     * 验证证书状态是否能够通过
     *
     * @param id
     * @return
     */
    @NLog
    @RequestMapping("/check_certificate")
    @ResponseBody
    public DggRestResponse checkCertificate(@RequestParam Long id) {
        try {
            GeneralCertificate credential = generalCredentialService.findCredentialById(id);
            // 证书状态为未使用 并且在库状态才能进行编辑
            ValidateUtils.isTrue(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(credential.getLibraryStatus()) && CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE.equals(credential.getCertificateStatus()), CertificateExcption.class, "该证书在使用或者已经出库不能进行编辑");
            return this.getSuccessResponse("验证通过");
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return this.getFailResponse(c.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }


    /**
     * 编辑证书
     *
     * @param generalCertificate
     * @param params
     * @return
     */
    @NLog()
    @RequestMapping(value = "/edit_certificate", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse editCertificate(GeneralCertificate generalCertificate, @RequestParam Map params) throws ParseException, IllegalAccessException, InvocationTargetException {
        try {
            // debug
        } catch (CertificateExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
        generalCertificate.setGeneralType(CredentialConstant.GENERAL_CREDENTIAL);
        params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        List<StorageCapacity> storageCapacities = generalCredentialService.saveOrUpdateCertificate(generalCertificate, params);
        try {
            GeneralCertificate credential = generalCredentialService.findCredentialById(generalCertificate.getId());
            // 证书状态为未使用 并且在库状态,未过期才能进行匹配预约数据  如果过期的话不是证书过期就可以匹配预约数据
            if (CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN.equals(credential.getLibraryStatus()) && CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE.equals(credential.getCertificateStatus()) && (credential.getOverdueStatus().equals("1") || !("0".equals(generalCertificate.getOverdueStatus()) && generalCertificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL)))) {
                BaseCredential baseCredential = generalCredentialService.boundProductReservation(generalCertificate.getId(), storageCapacities, false);
                if (StringUtils.isNotEmpty(baseCredential)) {
                    params.put("msg", "证书编辑成功并已绑定生产订单[" + baseCredential.getScOrderNo() + "],点击确认跳转至证书信息列表！");
                }
            }
        } catch (CertificateExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("证书编辑成功，证书自动绑定预订生产订单失败！");
        }
        return this.getSuccessResponse("修改成功");
    }


    /**
     * 证书详情
     *
     * @param id
     * @return
     */
    @NLog()
    @RequestMapping("/credential_detail")
    public String CredentialDetail(@RequestParam Long id, Model model) {
        try {
            GeneralCertificate credential = generalCredentialService.findCredentialByIdWithTranslate(id);
            model.addAttribute("credential", credential);
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return "/error/401";
        } catch (Exception e) {
            e.printStackTrace();
            return "/error/401";
        }
        return "/zzsc/credential/generalCredential/certificate_detail";
    }


    /**
     * 证书收支记录
     *
     * @param params
     * @param request
     * @return
     */
    @NLog
    @RequestMapping("/accounts_detail")
    @ResponseBody
    public DggRestResponse accountsDetail(@RequestParam() Map params, HttpServletRequest request) {
        try {
            String ids = certificateProductService.findOrderIdsByCredentialId(Long.parseLong(params.get("id").toString()));
            Map param = new HashMap();
            if (StringUtils.isNotEmpty(ids)) {
                param = orfApiService.queryOrderBusinessPayment(ids, Integer.parseInt(params.get("accountsType").toString()));
            }
            return this.getSuccessResponse(param);
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * 退回证书重新入库页面
     *
     * @param certificateNo
     * @param productId
     * @return
     */
    @NLog
    @RequestMapping("/edit_return_credential_page")
    public String editReturnCredentialPage(@RequestParam String certificateNo, @RequestParam Long productId, Model model) {
        // 查询需要新增证书关联的订单详情
        Map map = new HashMap();
        map.put("productId", productId);
        List<OrderProductVo> products = productService.findWaitAddCredentailProduct(map);
        model.addAttribute("products", products.get(0));
        // 获取当前日期
        model.addAttribute("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));

        // 适用范围
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        // 证书类别
        List<Map> certificateCategorys = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_CATEGORY, 1, 2, null);
        model.addAttribute("certificateCategorys", certificateCategorys);
        // 三类证书
        List<Map> certificateToThrees = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_TO_THREE, 1, 2, null);
        model.addAttribute("certificateToThrees", certificateToThrees);
        // 是否购买社保
        List<CommonVo> socialSecurity = new ArrayList<>(2);
        CommonVo commonVo1 = new CommonVo("0","是");
        CommonVo commonVo2 = new CommonVo("1","否");
        socialSecurity.add(commonVo1);
        socialSecurity.add(commonVo2);
        model.addAttribute("socialSecurity", socialSecurity);
        GeneralCertificate credential = generalCredentialService.findCredentialByNo(certificateNo);
        model.addAttribute("credential", credential);
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        return "/zzsc/credential/generalCredential/edit_return_credential_page";
    }


    /**
     * 证书退回修改
     *
     * @param generalCertificate
     * @param params
     * @return
     */
    @NLog()
    @RequestMapping(value = "/edit_return_certificate", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse editReturnCertificate(GeneralCertificate generalCertificate, @RequestParam Map params) {
        try {
            generalCertificate.setGeneralType(CredentialConstant.GENERAL_CREDENTIAL);
            params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
            List<StorageCapacity> storageCapacities = generalCredentialService.UpdateReturnCertificate(generalCertificate, params);
            try {
                BaseCredential baseCredential = generalCredentialService.boundProductReservation(generalCertificate.getId(), storageCapacities, false);
                if (StringUtils.isNotEmpty(baseCredential)) {
                    params.put("msg", "证书重新入库并已绑定生产订单[" + baseCredential.getScOrderNo() + "],点击确认跳转至证书信息列表！");
                }
            } catch (CertificateExcption e) {
                return this.getFailResponse(e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                return this.getFailResponse("证书重新入库成功，证书自动绑定预订生产订单失败！");
            }
            return this.getSuccessResponse(params);
        } catch (CertificateExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * 查询证书的最新销售子订单数据
     *
     * @param id
     * @return
     */
    @NLog
    @RequestMapping("/find_order_business_by_certificate")
    @ResponseBody
    public DggRestResponse findOrderBusinessByCertificate(@RequestParam Long id) {
        try {
            Map map = new HashMap();
            map = generalCredentialService.findOrderBusinessInfoByCertificate(id);
            return this.getSuccessResponse(map);
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * 证书总览：证书信息统计
     *
     * @param param
     * @param request
     * @return
     */
    @NLog
    @RequestMapping("general_credential_count")
    @ResponseBody
    public DggRestResponse generalCredentialCount(@RequestParam Map param, HttpServletRequest request) {
        try {
            Map count = generalCredentialService.generalCredentialCount(param);
            return this.getSuccessResponse(count);
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }

    }

    /**
     * 证书总览：证书库容
     */
    @NLog
    @RequestMapping("/wanrning_count")
    @ResponseBody
    public DggRestResponse warningCount(@RequestParam Map params, HttpServletRequest request) {
        try {
            params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
            List<Map> count = storageCapacityService.generalCredentialWarningCount(params);
            return this.getSuccessResponse(count);
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /**
     * 证书总览：证书库容
     */
    @NLog()
    @RequestMapping("/wanrning_configure")
    @ResponseBody
    public DggRestResponse warningConfigure(@RequestParam Map params, HttpServletRequest request) {
        try {
            params.put("generalType", CredentialConstant.GENERAL_CREDENTIAL);
            List<Map> count = systemConfigureService.warningConfigure(params);
            return this.getSuccessResponse(count);
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }


    /**
     * 证书导出
     *
     * @param params
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export_all_credential")
    @ResponseBody
    @NLog()
    public void exportAll_credential(@RequestParam Map params, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<AllGeneralCredentialVo> list = generalCredentialService.queryExportAllCredential(params);
            String fileName = "证书信息列表全部导出" + DateUtils.dateString(new Date(), "yyyyMMddHHmm") + ".xlsx";
            ExcelUtils.writeToFile(list, null, fileName, response, AllGeneralCredentialVo.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 删除订单数据
     */
    @NLog()
    @RequestMapping("/del_order_business")
    @ResponseBody
    public DggRestResponse delOrderBusiness(@RequestParam Long orderBusinessId, HttpServletRequest request) {
        try {
            Product product = productService.delProduct(orderBusinessId);
            return this.getSuccessResponse("删除成功！");
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }


    /**
     * 取消证书装态
     *
     * @param certificateId
     * @return
     */
    @RequestMapping("/cancel_certificate_status")
    @ResponseBody
    @NLog
    public DggRestResponse cancelCertificateStatus(@RequestParam Long certificateId, @RequestParam(required = false) String certificateNo) {
        try {
            if(StringUtils.isEmpty(certificateNo)){
                GeneralCertificate generalCertificate = generalCredentialService.findCredentialByIdWithTranslate(certificateId);
                certificateNo = generalCertificate == null ? "" : generalCertificate.getCertificateNo();
            }
            generalCredentialService.cancelCertificateStatus(certificateId,certificateNo);
            return this.getSuccessResponse("删除成功！");
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }

    /*
     * @Author zsx
     * @Date 2018-11-13 09:11:53
     * @Description 证书使用页面初始化
     * @param certificateId 证书id
     * @return null
     */
    @RequestMapping("/affiliated_certificate_page")
    @NLog
    public String affiliatedCertificatePage(Model model, Long certificateId) {
        try {
            ValidateUtils.strNotEmpty(certificateId, CertificateExcption.class, "请选择证书");
            Map map = new HashMap<String, Object>() {{
                put("certificateId", certificateId);
            }};
            Map resultMap = guidePriceConfigService.countGuidePriceBySubordinate(map);
            if (resultMap != null) {
                model.addAttribute("hangUpGuidingPrice", resultMap.get("hangUpGuidingPrice"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/zzsc/credential/generalCredential/affiliated_certificate_page";
    }

    /**
     * 跳到企业续约
     * @param model
     * @param certificateId
     * @return
     */
    @RequestMapping("/business_renewal")
    @NLog
    public String businessRenewal(Model model, Long certificateId) {
        try {
            ValidateUtils.strNotEmpty(certificateId, CertificateExcption.class, "请选择证书");
            Map map = new HashMap<String, Object>() {{
                put("certificateId", certificateId);
            }};
            Map resultMap = guidePriceConfigService.countGuidePriceBySubordinate(map);
            if (resultMap != null) {
                model.addAttribute("hangUpGuidingPrice", resultMap.get("hangUpGuidingPrice"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/zzsc/credential/generalCredential/business_renewal";
    }

    /**
     * 跳到人才续约
     * @param model
     * @param certificateId
     * @return
     */
    @RequestMapping("/talent_renewal")
    @NLog
    public String talentRenewal(Model model, Long certificateId, Long id) {
        try {
            model.addAttribute("ceretificateId", DggKeyWorker.nextId());
            model.addAttribute("id", id);
            model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/zzsc/credential/generalCredential/talent_renewal";
    }

    /*
     * @Author zsx
     * @Date 2018-11-13 02:11:43
     * @Description 校验证书状态  是否可以进行使用
     * @param certificateId 证书id
     * @return null
     */
    @RequestMapping("/check_credential_status")
    @ResponseBody
    @NLog
    public DggRestResponse checkCredentialStatus(@RequestParam Long certificateId) {
        try {
            GeneralCertificate certificate = generalCredentialService.findCredentialById(certificateId);
            /*//验证事业部（已废弃）
            Long  orgId  = commonService.findUserSyb(sessionManager.getCurrentUser());
           if (!certificate.getSignOrgId().equals(orgId)){
               return this.getFailResponse("只能使用自己所属事业部的证书");
           }*/
            if ("0".equals(certificate.getOverdueStatus()) && certificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL)) {
                return this.getFailResponse("该证书已过期无法使用");
            }
            if (!certificate.getCertificateStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_STATUS_NO_USE)
                    || !certificate.getLibraryStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN)) {
                return this.getFailResponse("只能使用在库且未使用的证书！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
        return this.getSuccessResponse("");
    }

    /**
     * 企业续签验证证书使用状态，必须已使用
     * @param certificateId
     * @return
     */
    @RequestMapping("/check_business_status")
    @ResponseBody
    @NLog
    public DggRestResponse checkBusinessStatus(@RequestParam Long certificateId) {
        try {
            GeneralCertificate certificate = generalCredentialService.findCredentialById(certificateId);
//            if ("0".equals(certificate.getOverdueStatus()) && certificate.getOverdueType().contains(CredentialConstant.CREDENTIAL_OVER_DUE_TYPE_CREDENTIAL)) {
//                return this.getFailResponse("该证书已过期无法使用");
//            }
            if (!certificate.getCertificateStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_STATUS_SUBORDINATE)
                    || !certificate.getLibraryStatus().equals(CredentialConstant.GENERAL_CREDENTIAL_LIBRARY_STATUS_IN)) {
                return this.getFailResponse("只能续签在库且已使用的证书！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
        return this.getSuccessResponse("");
    }

    /*
     * @Author zsx
     * @Date 2018-11-13 03:11:58
     * @Description 证书使用
     */
    @RequestMapping("/save_certificates_attached")
    @ResponseBody
    @NLog()
    public DggRestResponse saveCertificatesAttached(@RequestParam Map params) {
        try {
            if (StringUtils.isEmpty(params.get("certificateId"))){
                return this.getFailResponse("证书id不能为空");
            }
            if (StringUtils.isEmpty(params.get("scOrderId"))){
                return this.getFailResponse("生产订单id不能为空");
            }
            generalCredentialService.saveCertificatesAttached(params);
        } catch (ProductOrderExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
        return this.getSuccessResponse("使用成功");
    }

    /**
     * 保存企业续签
     * @param params
     * @return
     */
    @RequestMapping("/save_business_renewal")
    @ResponseBody
    @NLog()
    public DggRestResponse saveBusinessRenewal(@RequestParam Map params) {
        try {
            if (StringUtils.isEmpty(params.get("certificateId"))){
                return this.getFailResponse("证书id不能为空");
            }
            if (StringUtils.isEmpty(params.get("scOrderId"))){
                return this.getFailResponse("生产订单id不能为空");
            }
            generalCredentialService.saveBusinessRenewal(params);
        } catch (ProductOrderExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
        return this.getSuccessResponse("企业续签成功");
    }

    @RequestMapping("/update_certificates_phone")
    @ResponseBody
    public DggRestResponse updateCertificatesPhone(){
        try {
           generalCredentialService.updateGertificatePhone();
            return this.getSuccessResponse("修改成功");
        }catch (Exception e){
            return this.getFailResponse("修改失败");
        }
    }
    /**
     * 查看号码
     * @param id
     * @return
     */
    @RequestMapping(value="/see_number")
    @ResponseBody
    public DggRestResponse seeNumber(@RequestParam Long id){
        try {
            String returnStr = generalCredentialService.getPersonalPhone(id);
            return this.getSuccessResponse(returnStr);
        }catch(Exception e){
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }

    /**
     * 跳到入库管理
     * @param model model对象
     * @return 页面路径
     */
    @RequestMapping("/warehousing")
    @NLog
    public String talentRenewal(Model model) {
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        return "/zzsc/credential/generalCredential/warehousing";
    }

    /**
     * 证书信息列表数据
     *
     * @param params
     * @param request
     * @return
     */
    @NLog()
    @RequestMapping("/warehousing_data")
    @ResponseBody
    public DataTableResponse warehousingData(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        Warehousing warehousing = new Warehousing();
        warehousing.setPage(r.getPage()-1);
        warehousing.setLimit(r.getLength());
        warehousing.setCertificateType((String) params.get("certificateType1"));
        warehousing.setCertificateSpecialtys((String) params.get("certificateSpecialtys1"));
        warehousing.setCertificateLevel((String) params.get("certificateLevel1"));
        warehousing.setCertificateArea((String) params.get("certificateAreaId"));
        if (warehousing.getCertificateArea()!=null){
            Map<String, String> map = baseCredentialService.dealArea(params.get("areaName").toString(), params.get("certificateAreaId").toString());
            if (StringUtils.isNotEmpty(map)) {
                // 如果用户选择的是省/市
                warehousing.setAreaProvince(map.get("pcode").toString());
            } else {
                // 如果只选择了省
                warehousing.setAreaProvince(params.get("certificateAreaId").toString());
                warehousing.setCertificateArea(null);
            }
        }

        List<Warehousing> warehousingList = generalCredentialService.getWarehousingList(warehousing);
        int count= generalCredentialService.getCountWarehousingList(warehousing);
        params.put("page",r.getPage());
        params.put("limit", r.getLength());
        params.put("count", count);
        return new DataTableResponse().data(params, warehousingList);
    }

    /**
     * 跳到新增配置
     * @param model
     * @return
     */
    @RequestMapping("/add_warehousing")
    @NLog
    public String addWarehousing(Model model) {
        // 证书类别
        List<Map> certificateCategorys = commonService.queryTreeBook(CredentialConstant.GENERAL_CERTIFICATE_CATEGORY, 1, 2, null);
        model.addAttribute("certificateCategorys", certificateCategorys);
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        return "/zzsc/credential/generalCredential/add_warehousing";
    }

    /**
     * 保存新增
     * @param params
     * @return
     */
    @NLog()
    @RequestMapping(value = "/addWarehousing2", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse addWarehousing2(@RequestParam Map params) {
        String certificateSpecialty = params.get("certificateSpecialty").toString();
        Warehousing warehousing = new Warehousing();
        warehousing.setCertificateSpecialtys(certificateSpecialty);
        warehousing.setCertificateType(params.get("certificateType").toString());
        warehousing.setCertificateArea(params.get("certificateArea").toString());
        warehousing.setCertificateLevel(params.get("certificateLevel").toString());
        warehousing.setStockQuantity(Integer.parseInt(params.get("stockQuantity").toString()));
        warehousing.setApplicationScope(params.get("areaName").toString());
        Map<String, String> map = baseCredentialService.dealArea(params.get("areaName").toString(), params.get("certificateAreaId").toString());
        if (StringUtils.isNotEmpty(map)) {
            // 如果用户选择的是省/市
            warehousing.setAreaProvince(map.get("pcode").toString());
        } else {
            // 如果只选择了省
            warehousing.setAreaProvince(params.get("certificateAreaId").toString());
            warehousing.setCertificateArea(null);
        }
        boolean selectWarehousing = generalCredentialService.selectWarehousing(warehousing);
        if (selectWarehousing){
            return this.getFailResponse("地区、证书类型、专业、等级不可全部重复");
        }
        boolean b = generalCredentialService.addWarehousing2(warehousing);
        if (b){
            return this.getSuccessResponse("入库添加成功");
        }
        return this.getFailResponse("入库添加失败！");
    }

    /**
     * 保存修改
     * @param params
     * @return
     */
    @NLog()
    @RequestMapping(value = "/updateWarehousing", method = RequestMethod.POST)
    @ResponseBody
    public DggRestResponse updateWarehousing(@RequestParam Map params) {
        String certificateSpecialty = params.get("certificateSpecialty").toString();
        Warehousing warehousing = new Warehousing();
        warehousing.setId(Long.parseLong(params.get("id").toString()));
        warehousing.setCertificateSpecialtys(certificateSpecialty);
        warehousing.setCertificateType(params.get("certificateType").toString());
        warehousing.setCertificateArea(params.get("certificateArea").toString());
        warehousing.setCertificateLevel(params.get("certificateLevel").toString());
        warehousing.setStockQuantity(Integer.parseInt(params.get("stockQuantity").toString()));
        boolean b = generalCredentialService.updateWarehousing(warehousing);
        if (b){
            return this.getSuccessResponse("入库添加成功");
        }
        return this.getFailResponse("入库添加失败！");
    }

    /**
     * 跳到编辑配置
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/edit_warehousing")
    @NLog
    public String editWarehousing(Model model, Long id) {
        model.addAttribute("generalType", CredentialConstant.GENERAL_CREDENTIAL);
        Warehousing warehousing = generalCredentialService.findWarehousingById(id);
        model.addAttribute("warehousing", warehousing);
        return "/zzsc/credential/generalCredential/edit_warehousing";
    }

    /**
     * 修改证书装态
     *
     * @param ids
     * @return
     */
    @RequestMapping("/update_certificate_status")
    @ResponseBody
    @NLog
    public DggRestResponse updateCertificateStatus(@RequestParam String ids) {
        try {
            generalCredentialService.updateCertificateStatus(ids);
            return this.getSuccessResponse("修改成功！");
        } catch (CertificateExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (CommonExcption e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return this.getFailResponse("系统错误，请联系管理员");
        }
    }
}

